/**
 * 上传组件UI，对webuploader.js进行封装
 */
var _myUploader_sa = document.getElementsByTagName('script');
var _myUploader_path = _myUploader_sa[_myUploader_sa.length - 1].src;
_myUploader_path = _myUploader_path.substring(0, _myUploader_path.lastIndexOf('/'));
(function (W, $) {
	W.myUploader = function(container, settings){
		var defaultOptions = {
			basepath: UiUtil.path,
			filepath: UiUtil.path+'/files',//存放文件的路径，文件访问url为filepath+'/'+uploadDir+'/'+data.fileName
			uploadDir: null,
			data: null,//初始化数据：[{"id":"","fileName":"","origName":"","fileDesc":"",,"fileSize":"""thumb":""}]；id和fileName为必须字段
			thumb : true,	//是否创建缩略图
			errImg: UiUtil.path +'/res/img/noimg.jpg',
			canEditDesc: false,//是否可以修改文件描述
			type: "myupload",//类型
			single: false,
			field: null,
			//webUploader的配置信息
			webUploader:{
				swf: _myUploader_path+'/Uploader.swf',
				server: UiUtil.path+'/myupload.json',
				accept: null,
			    fileVal: 'uploadFile',//文件上传域的name
			    formData: {},//文件上传请求的参数表，每次发送都会发送此对象中的参数
			    fileNumLimit: null,//文件总数量, 超出则不允许加入队列
				fileSizeLimit: null,//文件总大小, 超出则不允许加入队列
				fileSingleSizeLimit:null,//单个文件大小, 超出则不允许加入队
				compress: false,
				duplicate: true//去重
			},
			
			onUploadSuccess: null,
			onCancel: null,
			onDelete: null
		};
		this.options = $.extend(true, {}, defaultOptions, settings);
		this.container = container;
		var g = this, p = this.options;
		
		//是否上传完成
		g.isCompleted = function(){
			if(g._selectFileNums == g._uploadFileNums){
				return true;
			}
			return false;
		};
		
		g.isDone = function(){
			if(g.isCompleted()){
				return true;
			}
			errAlert("还有文件没有完成上传.");
			return false;
		};
		
		//初始化
		g._init=function(){
			if(!g.container.hasClass('myuploader')){
				g.container.addClass('myuploader');
			}
			
			if(g.container.hasClass('myuploader-single')){
				p.single = true;
				g.container.removeClass('myuploader-single');
			}
			
			if(p.single){
				p.webUploader.fileNumLimit = 1;
				if(!p.field){
					var cid = g.container.attr('id');
					if(cid){
						p.field = cid;
					}
				}
				if(p.data){
					if(typeof p.data == 'string'){
						p.data = $.parseJSON($.trim(p.data));
					}
				}else if(p.value){
					p.data = [{fileName: p.value, fileId: 'single'}];
				}else{
					var _tdata = $.trim(g.container.html());
					if(_tdata){
						if(_tdata.charAt(0)=='['){
							p.data = $.parseJSON(_tdata);
						}else{
							p.data = [{fileName: _tdata, fileId: 'single'}];
						}
					}
				}
			}else{
				if(p.data){
					if(typeof p.data == 'string'){
						p.data = $.parseJSON($.trim(p.data));
					}
				}else{
					var _tdata = $.trim(g.container.html());
					if(_tdata){
						p.data = $.parseJSON(_tdata);
					}
				}
			}
			
			g.container.empty();
			
			g.filelist = $('<div class="uploader-list"></div>');
			g.btns = $('<div class="uploader-btns"></div>');
			g.picker = $('<div class="picker">选择文件</div>');
			g.uploadBtn = $('<div class="picker webuploader-container disable"><div class="webuploader-pick">开始上传</div></div>');
			g.dels = $('<div class="uploader-dels"></div>');
			
			g.btns.append(g.picker).append(g.uploadBtn);
			
			g.container.append(g.filelist).append(g.btns).append(g.dels);
			
			if(p.single && p.field){
				g.dels.append('<input type="hidden" id="'+p.type+p.field+'" name="'+p.field+'" />');
			}
			

			g._selectFileNums = 0;
			g._uploadFileNums = 0;
			g._uploaded = {};
			
			g._createUploader();
			
			g._renderInitData();
			
			g.uploadBtn.click(function(){
				if(!g.uploadBtn.hasClass("disable")){
					g.uploader.upload();
				}
			});
			
		};
		
		g._createUploader = function(){
			var opts = $.extend(true, {}, p.webUploader, {pick: g.picker[0]});
			var uploader = g.uploader = WebUploader.create(opts);
			
			//当文件被加入队列以后触发
			uploader.on("fileQueued", function(file){
				var html = [];
				html.push('<div id="file'+p.type + file.id + '" class="afile">');
				html.push('<div class="cols cols-img">');
				if(g._isImg(file.name)){
					html.push('<img />');
				}else{
					html.push('<span>无预览</span>');
				}
				html.push('</div>');
				html.push('<div class="cols cols-file">');
				html.push('<p>文件名:<b>状态：<span class="status">等待上传</span></b></p>');
				html.push('<input type="text" id="fd'+p.type + file.id + '" name="'+p.type+'_fileDesc" class="fd" noLiger="noLiger" />');
				html.push('<input type="hidden" id="fo'+p.type + file.id + '" name="'+p.type+'_origName" class="fo" />');
				html.push('<input type="hidden" id="fn'+p.type + file.id+ '" name="'+p.type+'_fileName" class="fn" />');
				html.push('<input type="hidden" id="fs'+p.type + file.id+ '" name="'+p.type+'_fileSize" class="fs" />');
				html.push('</div>');
				html.push('<div class="cols cols-btn">');
				html.push('<a href="javascript:;" class="auploadDel">删除</a>');
				html.push('</div>');
				html.push('<div style="clear:both;"></div>');
				html.push('</div>');
				
				var afile = $(html.join(""));
				g.filelist.append(afile);
				
				if(p.single){
					afile.addClass("afile-single");
				}
				
				if(!p.canEditDesc){
					$('#fd'+p.type+file.id).prop("readonly", true);
				}
				$('#fd'+p.type+file.id).val(file.name);
				$('#fo'+p.type+file.id).val(file.name);
				$('#fs'+p.type+file.id).val(file.size);
				
				if(g._isImg(file.name)){
					var img = $(".cols-img img", afile);
					uploader.makeThumb(file, function(error, src) {
				        if(error){
				        	img.replaceWith('<span>不能预览</span>');
				            return;
				        }
				        img.attr("src", src);
				    }, 80, 50);
				}
				$('.auploadDel', afile).data("fileId", file.id).click(function(){
					uploader.removeFile($(this).data("fileId"), true);
				});
				g.uploadBtn.removeClass("disable");
				g._selectFileNums++;
				g._checkLimit();
			});
			//当文件被移除队列后触发
			uploader.on("fileDequeued", function(file){
				$('#file'+p.type+file.id).remove();
				g._selectFileNums--;
				if(g._uploaded[''+file.id]){
					g._uploadFileNums--;
				}
				if(p.single && p.field){
					$('#'+p.type+p.field).val('');
					$('#'+p.type+p.field).focus().blur();
				}
				g._checkLimit();
			});
			//当开始上传流程时触发
			uploader.on("startUpload", function(){
				g.uploadBtn.addClass("disable");
			});
			//某个文件开始上传前触发
			uploader.on("uploadStart", function(file){
			});
			//上传过程中触发，携带上传进度
			uploader.on("uploadProgress", function(file, percentage){
				$('#file'+p.type+file.id).find('.status').html("上传中 "+parseInt(percentage * 100)+"%");
			});
			//当某个文件上传到服务端响应后，会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为false, 则此文件将派送server类型的uploadError事件
			uploader.on("uploadAccept", function(object, ret){
				if(ret.code && ret.code==200){
					return true;
				}
				return false;
			});
			//当文件上传成功时触发
			uploader.on("uploadSuccess", function(file, response){
				var afile = $('#file'+p.type+file.id);
				afile.find('.status').html("已上传");
				afile.find('.fn').val(response.fileName);
				//afile.find('.fo').val(response.origName);
				afile.find('.fs').val(response.fileSize);
				if(p.single && p.field){
					$('#'+p.type+p.field).val(response.fileName);
					$('#'+p.type+p.field).focus().blur();
				}
				g._uploadFileNums++;
				g._uploaded[''+file.id] = true;
			});
			//当文件上传出错时触发
			uploader.on("uploadError", function(file, reason){
				$('#file'+p.type+file.id).find('.status').html("上传出错["+reason+"]");
			});
			//当开始上传流程暂停时触发
			//uploader.on("stopUpload", function(){
			//	g.uploadBtn.removeClass("disable");
			//});
			//当所有文件上传结束时触发
			uploader.on("uploadFinished", function(){
				g.uploadBtn.removeClass("disable");
			});
			
		};
		
		//设置初始化数据
		g._renderInitData = function(){
			if(!p.data || !p.data.length){
				return;
			}
			for(var i=0; i<p.data.length; i++){
				var d = p.data[i];
				var html = [];
				html.push('<div id="file'+p.type + d.fileId + '" class="afile">');
				html.push('<div class="cols cols-img">');
				if(g._isImg(d.fileName)){
					html.push('<img src="'+p.filepath+'/'+p.uploadDir+'/'+(d.thumb || d.fileName)+'" />');
				}else{
					html.push('<span>无预览</span>');
				}
				html.push('</div>');
				html.push('<div class="cols cols-file">');
				html.push('<p>文件名:<b>状态：<span class="status">已上传</span></b></p>');
				html.push('<input type="text" id="fd'+p.type + d.fileId + '" name="'+p.type+'_mFileDesc" class="fd" noLiger="noLiger" />');
				html.push('<input type="hidden" id="fo'+p.type + d.fileId + '" name="'+p.type+'_mOrigName" class="fo" />');
				html.push('<input type="hidden" id="fn'+p.type + d.fileId+ '" name="'+p.type+'_mFileName" class="fn" />');
				html.push('<input type="hidden" id="fi'+p.type + d.fileId+ '" name="'+p.type+'_mFileId" class="fn" />');
				html.push('</div>');
				html.push('<div class="cols cols-btn">');
				html.push('<a href="javascript:;" class="auploadDel">删除</a>');
				html.push('</div>');
				html.push('<div style="clear:both;"></div>');
				html.push('</div>');
				
				var afile = $(html.join(""));
				g.filelist.append(afile);
				
				if(p.single){
					afile.addClass("afile-single");
				}
				
				if(!p.canEditDesc){
					$('#fd'+p.type+d.fileId).prop("readonly", true);
				}
				$('#fd'+p.type+d.fileId).val(d.fileDesc || d.fileName);
				$('#fo'+p.type+d.fileId).val(d.origName || d.fileName);
				$('#fn'+p.type+d.fileId).val(d.fileName);
				$('#fi'+p.type+d.fileId).val(d.fileId || '');
				
				$('.auploadDel', afile).data("fileId", d.fileId).click(function(){
					var fileId = $(this).data("fileId") || '';
					g.dels.append('<input type="hidden" id="'+p.type+'_delId_'+fileId+'" name="'+p.type+'_delId" value="'+fileId+'" />');
					$('#file'+p.type+fileId).remove();
					if(p.single && p.field){
						$('#'+p.type+p.field).val('');
						$('#'+p.type+p.field).focus().blur();
					}
					g._checkLimit();
				});
				
				if(p.single && p.field){
					$('#'+p.type+p.field).val(d.fileName);
					$('#'+p.type+p.field).focus().blur();
					break;
				}
			}
			
			g._checkLimit();
		};
		
		g._checkLimit=function(){
			if(p.webUploader.fileNumLimit){
				if($('.afile', g.container).size() >= p.webUploader.fileNumLimit){
					window.setTimeout(function(){g.picker.hide();}, 100);
				}else{
					g.picker.show();
				}
			}
		};
		
		//判断是否为一个图片文件
		g._isImg=function(fileName){
			if(fileName && (/.+\.(png|jpg|jpeg|gif|bmp)$/gi).test(fileName)){
				return true;
			}
			return false;
		};
		
		g._init();
	};
	
	$.fn.myUploader=function(settings){
		return new myUploader(this, settings);
	};
	$.fn.myImgUploader=function(settings){
		var options = $.extend(true, {}, settings, {
			webUploader:{
				accept:{
					title: "Images",
					extensions: "jpg,jpeg,png,gif,bmp",
					mimeTypes: "image/jpg,image/jpeg,image/png,image/gif,image/x-ms-bmp"
				}
		}});
		return new myUploader(this, settings);
	};
	$.fn.myDocUploader=function(settings){
		var options = $.extend(true, {}, settings, {
			webUploader:{
				accept:{
					title: "文档文件",
					extensions: "doc,docx,xls,xlsx,ppt,pptx,pdf,rtf,txt",
					mimeTypes: "application/msword,"
						+"application/vnd.openxmlformats-officedocument.wordprocessingml.document,"
						+"application/vnd.ms-excel,"
						+"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,"
						+"application/vnd.ms-powerpoint,"
						+"application/vnd.openxmlformats-officedocument.presentationml.presentation,"
						+"application/pdf,"
						+"application/rtf,"
						+"text/plain"
				}
		}});
		return new myUploader(this, settings);
	};
	
})(window, jQuery);
